var portFolioItem= function(id,excRate, stake,trading){
	var self= this;
	self.ID= ko.observable(id);
	self.currPr= ko.observable(excRate);
	self.stake= ko.observable(stake);
	self.trading= ko.observable(trading);
	self.lastMove= ko.observable();
	self.direction= ko.observable();
	self.inputValue= ko.observable(1);
	self.legalSell= ko.observable(true);
	self.legalBuy= ko.observable(true);
	self.illegal= ko.observable(false);
	self.classUp= ko.computed(function(){
		if(self.direction() === 'UP')
			return true;
		return false;
	});
	self.classDwn= ko.computed(function(){
		if(self.direction() === 'DW')
			return true;
		return false;
	});
	self.roundNumber= function(num, dec) {
		return Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	};
	self.currValue= ko.computed(function(){
		return self.roundNumber(self.currPr() * self.stake(),3);
	});
	self.legal= function(){
		//eequitie is not trading, stopp all 
		if(self.trading() === false){
			//console.log("	" + self.ID() + "trading closed");
			self.legalSell(false);
			self.legalBuy(false);
			self.illegal(true);
			return
		}
		//no sell state
		//console.log("	" + self.ID() + "sell state check");
		if(self.inputValue() > self.stake() || self.inputValue() < 1 || self.inputValue() === "")
			self.legalSell(false);
		else
			self.legalSell(true);
		//no buy state
		//console.log("	" + self.ID() + "buy state check");
		if((self.inputValue()*self.currPr()) > now.credit || self.inputValue() < 1 || self.inputValue() === "")
			self.legalBuy(false);
		else		  				
			self.legalBuy(true);
		//marker to mark an illegal state		  			
		if(self.legalSell() == false || self.legalBuy() == false)
			self.illegal(true);
		else	
			self.illegal(false);
	}
	self.buy= function(){
		console.log("buy: " + self.ID() + self.inputValue());
		var worth= parseInt(self.inputValue()) * self.currPr();
		var inp= self.inputValue();
		self.stake(self.stake()+ parseInt(inp));
		self.inputValue("");
		now.credit-= worth;
		self.legal();
		now.sendStuff({'ID':self.ID(), 'units':inp,'act':'buy'});
		
	};
	self.sell= function(){
		console.log("sell: " + self.ID() + self.inputValue());
		var worth= self.inputValue() * self.currPr();
		var inp= self.inputValue();
		self.stake(self.stake()-inp);
		self.inputValue("");
		now.credit+= worth;
		self.legal();
		now.sendStuff({'ID':self.ID(), 'units':inp,'act':'sell'});
		
	};
	self.updatePrice= function(obj){
		self.currPr(obj.pr);
		self.lastMove(obj.mv);
		self.direction(obj.dir);
		self.trading(obj.mOpen);
	}
	self.getValue= function(){
		return self.currValue();
	}
	self.evaluate = ko.computed({
        read: function () {
            if(isNaN(self.inputValue()) === true)
            	return "";
            return self.inputValue(); 
        },
        write: function (value) {
        	if(isNaN(value) === true)
        		value="";
        	self.inputValue(value);
        	console.log(self.inputValue() + " self.legal is next:");
        	self.legal();
        },
        owner: self
    });
};
//TODO: make a mapper that maps the complex objects into observables	
var globalViewModel= function(p){
	var self = this;
	self.remTime= ko.observable(p.remTime);
	self.timeMsg= ko.computed(function(){
		if(self.remTime() > 0)
			return "Trading stops in " + self.remTime() + " minutes!";
		else
			console.log('Disabling trading ');
			$('.transActBtn, .inputValue, #addLineBtn,form_addPortf ').attr('disabled', 'disabled').addClass('ui-state-disabled ui-button-disabled');
			return "Trading has closed for this session. To try again hit refresh. ";
		});
	self.serverMsg= ko.observable(p.msg);
	self.marketOpen= ko.observable(p.marketOpen);
	self.equities= ko.observableArray(p.equities);		//making this into an observable objects list??
	self.eqList= ko.observableArray();
	self.traders= ko.observableArray(p.traders);
	self.username= ko.observable(now.name);
	self.credit= ko.observable(now.credit);
	self.initCredit= now.credit;
	self.portfolio= ko.observableArray(now.portfolio);
	self.toAdd= ko.observable();
	self.isUpToDate=ko.observable(false); 
	self.setup= function(){
		console.log("globalViewModel setup func");
		for(i=0;i<self.equities().length;i++){
			self.eqList().push(self.equities()[i]);
		}
		
	};
	self.roundNumber= function(num, dec) {
		return Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	};
	self.updatePortfolio= function(){
		for(i=0;i<self.portfolio().length;i++){
			tmpP= self.portfolio()[i];
			tmpP.updatePrice(self.findPriceById(tmpP.ID()));
		}
		self.isUpToDate(true);
		var obj= {'credit':self.pCredit(), 'value':self.pValue(),'total':self.pTotal(),'margin':self.pMargin()};
		now.commitPortf(obj);
		return true;
	};
	self.findPriceById= function(ident){
		for(i=0;i<self.equities().length;i++){
			tmpE= self.equities()[i];
			if((tmpE.ID) === ident){
				obj= {"pr":tmpE.currPr ,"mv":tmpE.lastMove ,"dir":tmpE.direction, "mOpen":self.marketOpen()};
				return obj;
			}
		}
		return -1;
	}
	self.pCredit= ko.computed(function(){
		return self.roundNumber(self.credit(),2);
	});
	self.pValue= ko.computed(function(){
		var rslt=0;
		for(i=0;i<self.portfolio().length;i++){
			rslt+= self.portfolio()[i].currValue();
		}
		return self.roundNumber(rslt,2);
	});
	self.pTotal= ko.computed(function(){
		return self.roundNumber((self.pValue() + self.credit()),2);
	});
	self.pMargin= ko.computed(function(){
		return self.roundNumber((self.pTotal()/self.initCredit),3);
	});
		   			
	self.getPortfolio= function(){
		return{"userName":now.name ,"credit":now.credit, "portfolio":self.portfolio()};
	};
	self.setUser= function(un){
		self.credit(un);
	};
	self.addLine= function(elem){
		if(self.marketOpen() === true){
			var tmp= self.toAdd();
			var pItem= new portFolioItem(tmp.ID, tmp.currPr, 0,self.marketOpen());
			pItem.legal();
			self.portfolio.push(pItem);
			self.eqList.remove(tmp);
			self.toAdd(undefined);
			self.updatePortfolio();
			$(' tbody.dsp-none').removeClass('dsp-none');
			setTimeout('$(".btnBuy").button({icons: {primary: "ui-icon-plusthick"},text:false});$(".btnSell").button({icons: {primary: "ui-icon-minusthick"},text:false});', 10);
		}
	};
	self.getExcRate= function(id){
		for(i=0;i<self.equities;i++){
			if(self.equities().ID == id){
				return self.equities().currPr;
			}
		}
	};
	
	self.setup();
};